<?php

require __DIR__ . "/../../vendor/autoload.php";

//流式调用示例Server-Sent Events
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
//header('Connection: keep-alive');
header('Access-Control-Allow-Origin: *');

function send_message($id, $data)
{
    echo "id: $id\n";
    echo "data: $data\n\n";
    ob_flush();
    flush();
}

send_message(time(), '连接已建立');

for ($i = 0; $i < 10; $i++) {
    send_message(time(), "消息 {$i}");
    sleep(1);
}

send_message(time(), '结束');

/**
 * 前端核心代码
    if (typeof (EventSource) !== "undefined") {
        var source = new EventSource("http://127.0.0.1/composer-package/examples/common-helpers/stream.php");
        source.onmessage = function (event) {
            console.log(event.data);
            if (event.data === "结束"){
                source.close();
            }
        };
    } else {
        console.log("您的浏览器不支持Server-Sent Events...");
    }
 * */



